package com.yansu.cloud.controller;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.yansu.cloud.bean.User;

/**
 * 
 * @author 言肃
 * @email yansu_code@126.com
 * @version 1.0
 * @date Jul 23, 2018 6:40:45 PM
 */
@RestController
public class RibbonController {

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private LoadBalancerClient loadBalancerClient; // ribbon客户端

	@GetMapping("/movie/{id}")
	public User findById(@PathVariable Long id) {
		// VIP: virtual IP
		return this.restTemplate.getForObject("http://microservice-provider-user/simple/" + id, User.class);
	}

	@GetMapping("/test")
	public String testRibbonConfig() {
		ServiceInstance serviceInstance = this.loadBalancerClient.choose("microservice-provider-user");
		System.out.println("111: " + serviceInstance.getHost() + ":" + serviceInstance.getPort() + ":"
				+ serviceInstance.getServiceId());
		ServiceInstance serviceInstance2 = this.loadBalancerClient.choose("microservice-provider-user2");
		System.out.println("222: " + serviceInstance2.getHost() + ":" + serviceInstance2.getPort() + ":"
				+ serviceInstance2.getServiceId());
		return "1";
	}

	@GetMapping("listAll")
	public List<User> listAll() {
		User[] users = this.restTemplate.getForObject("http://microservice-provider-user/listAll/", User[].class);
		return Arrays.asList(users);
	}

}
